<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <div class="header_title">
        {{titleName}}
      </div>
      <el-form :inline="true" :model="formInline" size="small">
        <el-form-item>
          <el-input style="width: 200px" v-model="formInline.name" placeholder="请输入二维码名称" @keyup.enter.native="listArray"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="listArray">搜索</el-button>
        </el-form-item>
        <div class="pull-right">
          <el-button  type="primary" size="small" @click="downloadAllQR()" style="margin-right: 10px">下载二维码</el-button>
          <el-button  type="primary" size="small" @click="addQR()">新建二维码</el-button>
        </div>
      </el-form>

      <el-table highlight-current-row :data="list" border size="mini" v-loading.body="listLoading">
        <el-table-column align="center" label='序号' width="50">
          <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
        </el-table-column>
        <el-table-column align="center" label="图片" prop="id">
          <template slot-scope="scope">
            <div  @click="viewCode(scope.row)">
              <vue-qr :text='links+"?storeId="+formInline.store_id+"&qrCode_id="+scope.row.id+"&activeId="+scope.row.active_id' :callback="getUrl" :qid="scope.row.id" :size="50" :margin="5"></vue-qr>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="二维码名称" prop="name"></el-table-column>
        <el-table-column align="center" label="类型" width="100px">
          <template slot-scope="scope">
            <div class="longlinks">{{scope.row.type==1?"微信":"支付宝"}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label='操作' width="330">
          <template slot-scope="scope">
            <el-button  type="primary" plain size="mini"  @click="downloadQR(scope.row)">下载</el-button>
            <el-button  type="primary" plain size="mini" @click="deleteQR(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹框 -->
    <el-dialog  title="新建二维码" :visible.sync="addTypeDialog" width="500px">
      <div class="main">
        <el-form :model="formdialog" :rules="rules" ref="formdialog">
          <el-form-item label="名称" prop="name">
            <el-input type="text" v-model="formdialog.name" style="width:88%"  placeholder="请输入二维码名称"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select
                placeholder="选择二维码类型"
                v-model="formdialog.type"
                style="width:88%"
                filterable
            >
              <el-option
                  v-for="item in typelist"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="main_botton">
          <el-button  type="primary"  @click="closeDialoig()">取消</el-button>
          <el-button  type="primary"  @click="save()">保存</el-button>
        </div>
      </div>
    </el-dialog>
    <!--二维码放大-->
    <el-dialog
      :title="codeName"
      :visible.sync="codeBox"
      width="30%"
      style="text-align:center;"
     >
      <vue-qr :text='links+"?storeId="+formInline.store_id+"&qrCode_id="+codeId+"&activeId="+activeId' :activeId="activeId" :callback="getUrl" :qid="codeId" :size="240" :margin="10"></vue-qr>
    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
                     layout="prev, pager, next, jumper" :page-count="totalDataNumber">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import {
  getLinkInfo,
  getLinkInfoPage,
  create_qr_code,
  del_qr_code,
} from "@/api/operation/manage_qr_code";
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import {
  linkName, notCharmap
} from "@/utils/validate";
import VueQr from 'vue-qr'
import QRCode from "qrcode";
export default {
  name: 'manage_qr_code',
  components: {
      VueQr
  },
  data(){
    const vName = (rule, value, callback) => {
      if (value.length<1) {
        callback(new Error("请输入二维码名字（1-15个字符）"));
      } else {
        if (!notCharmap(value)) {
          callback(new Error("名称不能包含特殊字符"));
        } else {
          callback();
        }
      }
    };

    const vType = (rule, value, callback) => {
      if (!this.formdialog.type) {
        callback(new Error("请选择二维码类型"));
      } else {
        callback();
      }
    };

    const vLink = (rule, value, callback) => {
      if(!linkName(this.formdialog.link)){
        callback(new Error("请填写正确的链接"));
      }else{
        callback();
      }
    };

    return{
      links:"",
      list: null,  //数据
      titleName:"",
      listLoading: false,  //表格换场动画
      addTypeDialog: false, // 弹窗是否显示
      formInline: {
        name:"",
        type:'',
        store_id:""
      },
      typelist:[{id:1,name:"微信"},{id:2,name:"支付宝"}],
      currentPage: 1,
      totalDataNumber: 0,
      formdialog:{  
        name:"",
        link:"",
        type:""
      },
      rules: {
        name: [{ required: false, validator: vName, trigger: "blur" }],
        type: [{ required: false, validator: vType, trigger: "blur" }],
        link:[{ required: true, validator: vLink, trigger: "change" }]
      },
      codeBox:false, // 二维码弹窗是否显示
      codeId:'',//二维码放大弹窗 二维码id
      codeName:'', // 二维码名称
      activeId:""
    }
  },
  activated(){
    const _self=this;
    if(_self.$route.params.id){
      _self.titleName=_self.$route.params.name;
      _self.formInline.store_id=_self.$route.params.id;
    }
    this.links =   location.host.split(':')[0] == 'scfy.i3020.com' ? `https://${location.host}/sms/#/boon/`:`http://dev.hahaipi.com/sms/#/boon/`;
    this.listArray();
  },
  methods:{
    handleClose () {
        console.log('close event')
    },
    listArray(){  //获取数据
      this.listLoading = true;
      this.list = [];
      getLinkInfoPage(this.formInline).then(response=>{
        this.totalDataNumber = response.data.page / 1;
        if (this.totalDataNumber == 0) {
          this.listLoading = false;
        } else {
          getLinkInfo(this.formInline).then(res=>{
            this.list = res.data;
            this.listLoading = false;
          });
        }
      });
    },
    //删除二维码
    deleteQR(id){
      this.$confirm('删除后二维码不可恢复，是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del_qr_code({id:id}).then(res => {
          this.$message.success({message:res.message});
          this.listArray();
        })
      }).catch(() => {        
      });
       
    },
    save(){ //新建二维码
      this.$refs["formdialog"].validate((valid) => {
        if (valid) {
          create_qr_code({
            name:this.formdialog.name,
            type:this.formdialog.type,
            store_id:this.formInline.store_id,
          }).then(res=>{
            if(res.code==1){
              this.$message.success({message:res.message});
              this.$refs.formdialog.resetFields();
              this.addTypeDialog = false;
              this.listArray();
            }
          });
        }
      });
    },
    handleCurrentChange(val) {  //获取某个分页的数据
      this.listLoading = true;
      getLinkInfo(this.formInline,val).then(res=>{
        this.list = res.data;
        this.listLoading = false;
      }).catch(res => {
        this.listLoading = false;
      });
    },
    addQR(){
      this.addTypeDialog = true;
    },
    closeDialoig(){
      this.addTypeDialog = false;
    },
    //下载二维码
    downloadQR(data){
      let activeID = data.active_id?data.active_id:"";
      const link= this.links+"?storeId="+this.formInline.store_id+'&qrCode_id='+ data.id+'&activeId=' + activeID;
      const downloadName= data.name + (data.type==1?"(微信)":"(支付宝)");
      QRCode.toDataURL(link).then(url => {
        let link = document.createElement('a');
        link.download = downloadName; 	//下载的资源重命名
        link.href = url;
        link.click();
      }).catch(err => {
        this.$message.error(err);
      });
    },
    // 下载全部二维码
    downloadAllQR(){
      let qrList = [];
      getLinkInfo({
        name:"",
        type:'',
        store_id:this.formInline.store_id,
      },-1).then(res=>{
        let list = res.data;
        if(list.length > 0 ){
          new Promise((resolve)=> {
            for(let i=0;i<list.length;i++){
              let activeID = list[i].active_id?list[i].active_id:"";
              const link= this.links+"?storeId="+this.formInline.store_id+'&qrCode_id='+ list[i].id+'&activeId=' + activeID;
              console.log(link)
              const downloadName= list[i].name + (list[i].type==1?"(微信)":"(支付宝)");
              QRCode.toDataURL(link).then(url => {
                qrList.push({
                  name: downloadName,
                  baseImg: url
                })
              }).catch(err => {
                this.$message.error(err);
              });
            }
            resolve();
          }).then(()=>{
            this.downloadZip(qrList,this.titleName);
          })
        }else{
          this.$message.error("没有二维码");
        }
      });
    },
    downloadZip(qrList,downloadName) {
      let img_list  = qrList;
      let blogTitle = downloadName + "(二维码)" // 下载的文件夹名称
      let zip = new JSZip();
      let imgs = zip.folder(blogTitle)
      let baseList = []
      for (let i = 0; i < img_list.length; i++) {
        let name = img_list[i].name // 每张图片的名称
        let image = new Image()
        // 解决跨域 Canvas 污染问题
        image.setAttribute('crossOrigin', 'anonymous')
        image.onload = function() {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          let context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          let url = canvas.toDataURL() // 得到图片的base64编码数据 let url =
          canvas.toDataURL('image/png')
          baseList.push({ name: name, img: url.substring(22) })
          if (baseList.length === img_list.length) {
            if (baseList.length > 0) {
              for (let k = 0; k < baseList.length; k++) {
                imgs.file(baseList[k].name + '.png', baseList[k].img, {
                  base64: true
                })
              }
              zip.generateAsync({ type: 'blob' }).then(function(content) {
                FileSaver.saveAs(content, blogTitle + '.zip')
              })
            }
          }
        }
        image.src = img_list[i].baseImg = `${img_list[i].baseImg}`
      }
    },
    //得到二维码的url
    getUrl(dataUrl,id){ 
      this.list.forEach(item => {
        if(id == item.id){
          item.src = dataUrl;
          item.msrc = dataUrl;
        }
      })
    },
    // 点击弹出弹窗 放大二维码
    viewCode(row){
      this.codeBox = true;
      this.codeId = row.id;
      this.activeId = row.active_id;
      this.codeName = row.name;
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .header_title{
    font-size: 24px;
    font-weight: bold;
    color: #000000;
    height: 80px;
    line-height: 80px;
  }
.customContainer {
  overflow-y: auto;
}
.longlinks{
  display:-webkit-box;
  text-overflow:ellipsis;
  overflow:hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient:vertical;
}
.main{
  .main_botton{
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    button{
      width: 100px;
      height: 35px;
      line-height: 10px;
    }
  }
}
</style>
